"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 多节点写入
Case Name   : 备机子事务测试，savepoint, release savepoint 回滚事务，事务中读也转发到主机
Create At   : 2023/07/20
Owner       : opentestcase033
Description :
    1.修改enable_remote_execute参数值为on
    2.创建测试表
    3.备机开启事务，insert，savepoint, release savepoint 回滚事务
    4.查询表的内容
    5.查看主机日志
Expect      :
    1.修改成功
    2.执行成功
    3.成功
    4.成功
    5.事务内都写语句都转发到主机
History     :
    modified: 2025/03/05 modified by kyleze,参数值变化,优化用例
"""
import os
import time
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant

PrimarySh = CommonSH('PrimaryDbUser')


@unittest.skipIf(1 == PrimarySh.get_node_num(),
                 'Single node, and subsequent codes are not executed.')
class MultiNodeWrite(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f"-----{os.path.basename(__file__)} start-----")
        self.standby_node = Node('Standby1DbUser')
        self.primary_node = Node('PrimaryDbUser')
        self.standby_sh = CommonSH('Standby1DbUser')
        self.constant = Constant()
        self.common = Common('Standby1DbUser')
        self.common_pri = Common('PrimaryDbUser')
        self.table = 't_multi_node_write_case0072'
        self.new_log_dir = os.path.join(macro.PG_LOG_PATH,
                                        'pg_log_multi_node_write0072')
        self.enable_remote_execute = 'enable_remote_execute'
        self.log_statement = 'log_statement'
        self.log_directory = 'log_directory'
        self.remote_excute_default = self.common.show_param(
            self.enable_remote_execute)
        self.log_statement_default = self.common.show_param(self.log_statement)
        self.log_dir_default = self.common_pri.show_param(self.log_directory)
        shell_cmd = f"rm -rf {self.new_log_dir}"
        self.logger.info(shell_cmd)
        shell_msg = self.common_pri.get_sh_result(self.primary_node, shell_cmd)
        self.assertEquals('', shell_msg, '删除目录失败')

    def test_multi_node_write(self):
        step1 = "-----step1:修改enable_remote_execute参数值为on;expect:修改成功-----"
        self.logger.info(step1)
        result = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}=on')
        self.assertTrue(result, f'执行失败:{step1}')
        restart_res = self.standby_sh.restart_db_cluster()
        self.assertTrue(restart_res, f'执行失败:{step1}')
        time.sleep(5)
        status = self.standby_sh.exec_cm_ctl('query', '-Cv')
        self.logger.info(status)
        self.assertTrue("cluster_state   : Normal" in status, '集群状态异常')
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        self.assertEquals(show_remote_excute, 'on', f'执行失败:{step1}')
        result = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_statement}=all')
        self.assertTrue(result, f'执行失败:{step1}')
        result = PrimarySh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"{self.log_directory}='{self.new_log_dir}'", single=True)
        self.assertTrue(result, f'执行失败:{step1}')
        show_log_statement = self.common.show_param(self.log_statement)
        self.assertEquals(show_log_statement, 'all', f'执行失败:{step1}')
        show_log_directory = self.common_pri.show_param(self.log_directory)
        self.assertEquals(show_log_directory, self.new_log_dir,
                          f'执行失败:{step1}')

        step2 = "-----step2:创建表;expect:执行成功-----"
        self.logger.info(step2)
        sql_cmd = f'''drop table if exists {self.table};
        create table {self.table}(
        id int,transaction_id int,balance float) with(segment=on);'''
        sql_msg = self.standby_sh.execut_db_sql(sql_cmd)
        self.logger.info(sql_msg)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS,
                      sql_msg, f'执行失败:{step2}')
        time.sleep(2)

        step3 = "-----step3:备机开启事务，insert，savepoint, " \
                "release savepoint 回滚事务;expect:执行成功-----"
        self.logger.info(step3)
        sql_cmd = f'''begin;
        insert into {self.table}(id,transaction_id,balance) 
        values (0,0,100),(0,1,200),(1,0,300),(1,1,300);
        savepoint mypoint;
        insert into {self.table}(id,transaction_id,balance) 
        values (2,1,400),(2,2,500),(3,3,300),(3,4,600);
        select * from {self.table} order by 1;
        release savepoint mypoint;
        insert into {self.table}(id,transaction_id,balance) 
        values (4,1,700),(4,2,800),(5,3,300),(5,4,900);
        select id, balance from {self.table};
        rollback;'''
        sql_msg = self.standby_sh.execut_db_sql(sql_cmd)
        self.logger.info(sql_msg)
        self.assertEquals(3, sql_msg.count(self.constant.INSERT_SUCCESS_MSG),
                          f'执行失败:{step3}')
        self.assertIn('BEGIN', sql_msg, f'执行失败:{step3}')
        self.assertIn('SAVEPOINT', sql_msg, f'执行失败:{step3}')
        self.assertIn(self.constant.ROLLBACK_MSG, sql_msg, f'执行失败:{step3}')
        self.assertIn('RELEASE', sql_msg, f'执行失败:{step3}')
        self.assertIn('8 rows', sql_msg, f'执行失败:{step3}')
        self.assertIn('12 rows', sql_msg, f'执行失败:{step3}')

        step4 = "-----step4:查询表的内容;expect:执行成功-----"
        self.logger.info(step4)
        sql_msg = self.standby_sh.execut_db_sql(f"select * from {self.table}")
        self.logger.info(sql_msg)
        self.assertIn('0 rows', sql_msg, f'执行失败:{step4}')

        step5 = "-----step5:主机查看日志打印;expect:日志记录建立连接、" \
                "转发给主机、接受执行结果等libpqsw信息-----"
        self.logger.info(step5)
        time.sleep(15)
        shell_cmd = f"ls -t {self.new_log_dir}"
        self.logger.info(shell_cmd)
        shell_msg = self.common_pri.get_sh_result(self.primary_node, shell_cmd)
        logfile = os.path.join(self.new_log_dir, shell_msg.split()[-1])
        self.logger.info(logfile)
        shell_cmd = f"grep {self.primary_node.db_name} {logfile}"
        self.logger.info(shell_cmd)
        shell_msg = self.common_pri.get_sh_result(self.primary_node, shell_cmd)
        self.assertIn(
            f'LOG:  statement: select * from {self.table} order by 1',
            shell_msg, f'执行失败:{step5}')
        self.assertIn(f'LOG:  statement: select id, balance from {self.table}',
                      shell_msg, f'执行失败:{step5}')

    def tearDown(self):
        step6 = "-----step6:恢复参数;expect:恢复参数成功-----"
        self.logger.info(step6)
        drop_res = self.standby_sh.execut_db_sql(f"drop table {self.table}")
        self.logger.info(drop_res)
        result1 = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}={self.remote_excute_default}')
        restart_res = self.standby_sh.restart_db_cluster()
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        result2 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_statement}={self.log_statement_default}')
        result3 = PrimarySh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"{self.log_directory}='{self.log_dir_default}'", single=True)
        status = self.standby_sh.exec_cm_ctl('query', '-Cv')
        self.logger.info(status)
        self.assertTrue("cluster_state   : Normal" in status, '集群状态异常')
        show_log_statement = self.common.show_param(self.log_statement)
        show_log_directory = self.common_pri.show_param(self.log_directory)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, drop_res,
                      f'执行失败:{step6}')
        self.assertTrue(result1, f'执行失败:{step6}')
        self.assertTrue(restart_res, f'执行失败:{step6}')
        self.assertEquals(show_remote_excute, self.remote_excute_default,
                          f'执行失败:{step6}')
        self.assertTrue(result2, f'执行失败:{step6}')
        self.assertTrue(result3, f'执行失败:{step6}')
        self.assertEquals(show_log_statement, self.log_statement_default,
                          f'执行失败:{step6}')
        self.assertEquals(show_log_directory, self.log_dir_default,
                          f'执行失败:{step6}')
        self.logger.info(f"-----{os.path.basename(__file__)} end-----")
